package cn.xhy.material.service.pojectinfo;

import cn.xhy.material.controller.admin.pojectinfo.vo.PojectInfoPageReqVO;
import cn.xhy.material.controller.admin.pojectinfo.vo.PojectInfoSaveReqVO;
import cn.xhy.material.dal.dataobject.pojectinfo.ContractDO;
import cn.xhy.material.dal.dataobject.pojectinfo.CustomerProjectDO;
import cn.xhy.material.dal.dataobject.pojectinfo.PojectInfoDO;
import cn.xhy.material.dal.mysql.pojectinfo.ContractMapper;
import cn.xhy.material.dal.mysql.pojectinfo.CustomerProjectMapper;
import cn.xhy.material.dal.mysql.pojectinfo.PojectInfoMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.xhy.material.enums.ErrorCodeConstants.POJECT_INFO_NOT_EXISTS;


/**
 * 项目信息 Service 实现类
 *
 * @author xhy
 */
@Service
@Validated
public class PojectInfoServiceImpl implements PojectInfoService {

    @Resource
    private PojectInfoMapper pojectInfoMapper;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CustomerProjectMapper customerProjectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPojectInfo(PojectInfoSaveReqVO createReqVO) {
        // 插入
        PojectInfoDO pojectInfo = BeanUtils.toBean(createReqVO, PojectInfoDO.class);
        pojectInfoMapper.insert(pojectInfo);

        // 插入子表
        createContractList(pojectInfo.getId(), createReqVO.getContracts());
        createCustomerProjectList(pojectInfo.getId(), createReqVO.getCustomerProjects());
        // 返回
        return pojectInfo.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePojectInfo(PojectInfoSaveReqVO updateReqVO) {
        // 校验存在
        validatePojectInfoExists(updateReqVO.getId());
        // 更新
        PojectInfoDO updateObj = BeanUtils.toBean(updateReqVO, PojectInfoDO.class);
        pojectInfoMapper.updateById(updateObj);

        // 更新子表
        updateContractList(updateReqVO.getId(), updateReqVO.getContracts());
        updateCustomerProjectList(updateReqVO.getId(), updateReqVO.getCustomerProjects());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePojectInfo(Long id) {
        // 校验存在
        validatePojectInfoExists(id);
        // 删除
        pojectInfoMapper.deleteById(id);

        // 删除子表
        deleteContractByProjectInfoId(id);
        deleteCustomerProjectByProjectId(id);
    }

    private void validatePojectInfoExists(Long id) {
        if (pojectInfoMapper.selectById(id) == null) {
            throw exception(POJECT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public PojectInfoDO getPojectInfo(Long id) {
        return pojectInfoMapper.selectById(id);
    }

    @Override
    public PageResult<PojectInfoDO> getPojectInfoPage(PojectInfoPageReqVO pageReqVO) {
        return pojectInfoMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（销售合同） ====================

    @Override
    public List<ContractDO> getContractListByProjectInfoId(Integer projectInfoId) {
        return contractMapper.selectListByProjectInfoId(projectInfoId);
    }

    private void createContractList(Long projectInfoId, List<ContractDO> list) {
        list.forEach(o -> o.setProjectInfoId(projectInfoId));
        contractMapper.insertBatch(list);
    }

    private void updateContractList(Long projectInfoId, List<ContractDO> list) {
        deleteContractByProjectInfoId(projectInfoId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createContractList(projectInfoId, list);
    }

    private void deleteContractByProjectInfoId(Long projectInfoId) {
        contractMapper.deleteByProjectInfoId(projectInfoId);
    }

    // ==================== 子表（客户和项目关系） ====================

    @Override
    public List<CustomerProjectDO> getCustomerProjectListByProjectId(String projectId) {
        return customerProjectMapper.selectListByProjectId(projectId);
    }

    private void createCustomerProjectList(Long projectId, List<CustomerProjectDO> list) {
        list.forEach(o -> o.setProjectId(projectId));
        customerProjectMapper.insertBatch(list);
    }

    private void updateCustomerProjectList(Long projectId, List<CustomerProjectDO> list) {
        deleteCustomerProjectByProjectId(projectId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createCustomerProjectList(projectId, list);
    }

    private void deleteCustomerProjectByProjectId(Long projectId) {
        customerProjectMapper.deleteByProjectId(projectId);
    }

}
